<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 从多说评论系统获取评论信息到本地数据库
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~用不了~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */ 
class SaveCommentInfo2LocalFromSuoShuoController extends Controller {
 /**
     *
     * 获取评论数据
     *
     */
    function sync_log() {
        $secret = '68ca027eb484ddbcbc457f23def09066';
        $short_name = 'ibeginner';
        $last_log_id = '3';

        
        
        if (!$this->check_signature($_POST)) {  //  貌似不验证签名也行！！！
            
            $limit = 20;

            $params = array(
                'limit' => $limit,				
                'order' => 'asc',
                'Accept' => 'application/json', 
                'short_name ' => $short_name, 
                'secret' => $secret,
            );


            $posts = array();

            if (!$last_log_id)
                $last_log_id = 0;

            $params['since_id'] = $last_log_id;
            
            include('src-test/Requests-1.6.0/library/Requests.php');
            // Next, make sure Requests can load internal classes
            src-test\Request-1.6.0\library\Requests::register_autoloader();
            // Now let's make a request!
            $url = 'http://api.duoshuo.com/log/list.json?short_name=ibeginner&secret=68ca027eb484ddbcbc457f23def09066&limit=2';
            $request = Requests::get($url);
            $list = json_decode($request->body)->response;
            
            if (!isset($list)) {
                //处理错误,错误消息$response['message'], $response['code']
                //...
				echo '{"msg":"获取多说数据出错~~~"}';
            } else {
                //echo '{"msg":"Ok3"}';
                //遍历返回的response，你可以根据action决定对这条评论的处理方式。
                foreach($list as $log){

                    switch($log->action){
                        case 'create':
                            //这条评论是刚创建的
                            //echo '{"msg":"save2localsuccess!"}';
                            $this->saveCommentInfo2Local($log->action);
                            break;
                        case 'approve':
                            //这条评论是通过的评论
                            break;
                        case 'spam':
                            //这条评论是标记垃圾的评论
                            break;
                        case 'delete':
                            //这条评论是删除的评论
                            break;
                        case 'delete-forever':
                            //彻底删除的评论
                            break;
                        default:
                            break;
                    }

                    //更新last_log_id，记得维护last_log_id。（如update你的数据库）
//                    if (strlen($log['log_id']) > strlen($last_log_id) || strcmp($log['log_id'], $last_log_id) > 0) {
//                        $last_log_id = $log['log_id'];
//                    }

                    
                }
                echo '{"msg":"同步成功！！！"}';
            }
         } else {
            echo '{"msg":POST！！！"}';
         }
    }

    function saveCommentInfo2Local($val) {
        
        $mysql = new SaeMysql();
        $sql = "INSERT INTO `tp_leavemessage`(`action`) VALUES ('".$val."') ";
        $mysql->runSql($sql);
        if ($mysql->errno() != 0) {
            //die("Error:" . $mysql->errmsg());
            echo '{"msg":"'.$mysql->errmsg().'"}';
        }

        $mysql->closeDb();
    }

    /**
     *
     * 检查签名
     *
     */
    function check_signature($input){
        $secret = '68ca027eb484ddbcbc457f23def09066';
        $short_name = 'ibeginner';
        $last_log_id = '3';
        unset($input['signature']);
        $str = $input['signature'];
        ksort($input);
        $baseString = http_build_query($input, null, '&');
        $expectSignature = base64_encode($this->hmacsha1($baseString, $secret));
        if ($str !== $expectSignature) {
            return false;
        }
        return true;
    }

    // from: http://www.php.net/manual/en/function.sha1.php#39492
    // Calculate HMAC-SHA1 according to RFC2104
    // http://www.ietf.org/rfc/rfc2104.txt
    function hmacsha1($data, $key) {
        if (function_exists('hash_hmac'))
            return hash_hmac('sha1', $data, $key, true);

        $blocksize=64;
        if (strlen($key)>$blocksize)
            $key=pack('H*', sha1($key));
        $key=str_pad($key,$blocksize,chr(0x00));
        $ipad=str_repeat(chr(0x36),$blocksize);
        $opad=str_repeat(chr(0x5c),$blocksize);
        $hmac = pack(
                'H*',sha1(
                        ($key^$opad).pack(
                                'H*',sha1(
                                        ($key^$ipad).$data
                                )
                        )
                )
        );
        return $hmac;
    }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////
    function saveComment2Loacal($data) {
        $model = M("LeaveMessage");
        $d['action'] = $data->action;
        
        $model->add($d);
        //echo "======saveComment2Loacal======".$data->action;
    }
    
  
    
}
